package com.tyrone.concurrent.concurrentUtils;

import com.tyrone.concurrent.utils.SleepUtils;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * 同步屏障：线程都到达一个屏障（同步点）时被阻塞，直到所有的线程都到达同步点。
 * 当所有的线程都到达同步点之后，await()方法将不在阻塞线程，此时所有线程继续执行
 *
 * @author Tyrone
 * @date 2021/12/22 16:21
 */
public class CyclicBarrierTest {
    //设置同步点为3个线程
    static CyclicBarrier cyclicBarrier = new CyclicBarrier(3);

    public static void main(String[] args) throws Exception {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("线程1到达同步点");
                    cyclicBarrier.await();
                } catch (Exception e) {

                }
                System.out.println("线程1跨越同步点");
            }
        }).start();
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("睡眠开始");
                SleepUtils.second(5);
                System.out.println("睡眠结束");
                try {
                    System.out.println("线程2到达同步点");
                    cyclicBarrier.await();
                    System.out.println("线程2跨越同步点");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        System.out.println("Main到达同步点");
        cyclicBarrier.await();
        System.out.println("success!");

    }
}
